#pragma once

#include "uring_loop.h"
#include <iostream>
#include <unistd.h>

namespace co_async {
inline thread_local UringLoop loop{};

class FileHandle {
public:
  explicit FileHandle(int fd = -1) : m_fd(fd) {}
  FileHandle(FileHandle &&that) : m_fd(that.m_fd) { that.m_fd = -1; }
  FileHandle &operator=(FileHandle &&that) {
    m_fd = that.m_fd;
    that.m_fd = -1;
    return *this;
  }
  ~FileHandle() {
    if (m_fd != -1) {
      close(m_fd);
    }
  }
  int get_fd() const noexcept { return m_fd; }
  void release() { m_fd = -1; }

  Task<std::size_t> read(std::span<char> buf) {
    return uring_read(loop, m_fd, buf, -1);
  }

  Task<std::size_t> write(std::span<char> buf) {
    return uring_write(loop, m_fd, buf, -1);
  }

protected:
  int m_fd;
};
} // namespace co_async